package com.egoo.ticket.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.egoo.ticket.server.pojo.dto.MsgTemplateDto;
import com.egoo.ticket.server.pojo.entity.MsgTemplate;
import com.egoo.ticket.server.pojo.vo.MsgTemplateVo;
import com.egoo.ticket.server.service.IMsgTemplateService;
import com.egoo.ticket.server.utils.common.ConstantCode;
import com.egoo.ticket.server.utils.common.DbResponse;
import com.egoo.ticket.server.utils.common.ResponseConstant;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author donny
 * @since 2020-10-27
 */
@Log4j2
@RestController
@RequestMapping("/v1/msgTemplate")
@Api(value = "消息模板管理", tags = "消息模板",description = "消息模板管理")
public class MsgTemplateController extends BaseController{
	@Autowired
	private IMsgTemplateService iMsgTemplateService;


	@RequestMapping(method = RequestMethod.POST,value = "/insert")
	@ApiOperation(value = "新增消息模板",notes = "新增消息模板")
	public DbResponse insert(@RequestBody MsgTemplateDto msgTemplateDto){
		if (headerParamIsExist()){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"userId和tenantId不能为空");
		}
		String name = msgTemplateDto.getName();
		String templateType = msgTemplateDto.getTemplateType();
		String content = msgTemplateDto.getContent();
		msgTemplateDto.setUserId(userId)
				.setTenantId(tenantId);
		boolean b = checkIsExist(msgTemplateDto);
		if (b){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"该模板名称已存在,更换后重试");
		}
		if (StringUtils.isEmpty(name)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"模板名字不能为空");
		}
		if (StringUtils.isEmpty(templateType)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"模板类型不能为空");
		}
		if (StringUtils.isEmpty(content)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"模板内容不能为空");
		}

		DbResponse dbResponse = iMsgTemplateService.insertTemplate(msgTemplateDto);
		return dbResponse;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 检测模板名是否存在
	 * @Param:
	 * @return:
	 * @Date: 2020/10/27
	 */
	private boolean checkIsExist(MsgTemplateDto msgTemplateDto) {
		Integer id = msgTemplateDto.getId();
		MsgTemplate msgTemplate = new MsgTemplate();
		msgTemplate.setName(msgTemplateDto.getName())
					.setTenantId(msgTemplateDto.getTenantId());
		QueryWrapper<MsgTemplate> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(MsgTemplate::getName,msgTemplateDto.getName())
								.eq(MsgTemplate::getTenantId,msgTemplateDto.getTenantId());
		List<MsgTemplate> list = iMsgTemplateService.list(queryWrapper);
		if (id == null && !CollectionUtils.isEmpty(list)){
			return true;
		}
		if (id != null && !CollectionUtils.isEmpty(list)){
			List<Integer> collect = list.stream().filter(m ->{
				return !id.equals(m.getId());
			}).map(m -> m.getId()).collect(Collectors.toList());
			if (collect.contains(id)){
				return true;
			}
		}
		return false;
	}

	@RequestMapping(method = RequestMethod.POST,value = "/update")
	@ApiOperation(value = "更新消息模板",notes = "更新消息模板")
	public DbResponse update(@RequestBody MsgTemplateDto msgTemplateDto){
		if (headerParamIsExist()){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"userId和tenantId不能为空");
		}
		msgTemplateDto.setUserId(userId)
					  .setTenantId(tenantId);
		boolean b = checkIsExist(msgTemplateDto);
		if (b){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"该模板名称已存在,更换后重试");
		}
		DbResponse dbResponse = iMsgTemplateService.updateTemplate(msgTemplateDto);
		return dbResponse;
	}

	@RequestMapping(method = RequestMethod.POST,value = "/forbidden")
	@ApiOperation(value = "启用禁用消息模板",notes = "启用禁用消息模板")
	public DbResponse forbidden(@RequestBody MsgTemplateDto msgTemplateDto){
		try {
			if (headerParamIsExist()){
				return new DbResponse(ResponseConstant.RES_FAIL_CODE,"userId和tenantId不能为空");
			}
			msgTemplateDto.setUserId(userId)
					.setTenantId(tenantId);
			MsgTemplate msgTemplate = new MsgTemplate();
			msgTemplate.setStatus(msgTemplateDto.getStatus());
			QueryWrapper<MsgTemplate> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(MsgTemplate::getId,msgTemplateDto.getId());
			boolean b = iMsgTemplateService.update(msgTemplate, queryWrapper);
			if (ConstantCode.STATUS_NOMAL_OLD.equals(msgTemplateDto.getStatus()) && b){
				return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,"启用");
			}
			if (ConstantCode.STATUS_CLOSED_OLD.equals(msgTemplateDto.getStatus()) && b){
				return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,"禁用");
			}
		} catch (Exception e) {
			log.info("执行异常"+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"执行异常");
		}
		return null;
	}

	@RequestMapping(method = RequestMethod.POST,value = "/delete")
	@ApiOperation(value = "删除消息模板",notes = "删除消息模板")
	public DbResponse delete(@RequestBody MsgTemplateDto msgTemplateDto){
		if (CollectionUtils.isEmpty(msgTemplateDto.getIds())){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"请先选择要删除的项");
		}
		boolean b = false;
		try {
			QueryWrapper<MsgTemplate> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().in(MsgTemplate::getId,msgTemplateDto.getIds());
			b = iMsgTemplateService.remove(queryWrapper);
		} catch (Exception e) {
			log.info("删除异常"+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"删除异常");
		}
		if (!b){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,ResponseConstant.DEL_FAIL_MSG);
		}
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.DEL_SUCCESS_MSG);
	}
	@RequestMapping(method = RequestMethod.GET,value = "/byId")
	@ApiOperation(value = "通过id查询消息模板",notes = "通过id查询消息模板")
	public DbResponse byId(@RequestParam("id") Integer id){
		if (headerParamIsExist()){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"userId和tenantId不能为空");
		}
		if (id == null){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"模板id不能为空");
		}
		MsgTemplate msgTemplate = null;
		try {
			msgTemplate = iMsgTemplateService.getById(id);
		} catch (Exception e) {
			log.info("查询异常"+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"查询异常");
		}
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,msgTemplate);
	}

	@RequestMapping(method = RequestMethod.POST,value = "/getList")
	@ApiOperation(value = "消息模板列表查询",notes = "消息模板列表查询")
	public DbResponse getList(@RequestBody MsgTemplateDto msgTemplateDto){
		if (headerParamIsExist()){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"userId和tenantId不能为空");
		}
		msgTemplateDto.setTenantId(tenantId)
						.setUserId(userId);
		try {
			List<MsgTemplateVo> list = iMsgTemplateService.getList(msgTemplateDto);
//			List<MsgTemplate> msgTemplates = msgTemplateIPage.getRecords();
//			msgTemplates = translateMsgType(msgTemplates);
			PageInfo<MsgTemplateVo> pageInfo = new PageInfo<>(list);
			long total = pageInfo.getTotal();
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,list,total);
		} catch (Exception e) {
			e.printStackTrace();
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,ResponseConstant.SELECT_FAIL_MSG);
		}

	}

	@RequestMapping(method = RequestMethod.GET,value = "/getByTemplateType")
	@ApiOperation(value = "通过模板类型查询",notes = "通过模板类型查询")
	public DbResponse getByTemplateType(@RequestParam("msgTemplateType")String msgTemplateType) {

		if (headerParamIsExist()){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"userId和tenantId不能为空");
		}
		if (StringUtils.isEmpty(msgTemplateType)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"消息模板类型不能为空");
		}
		QueryWrapper<MsgTemplate> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda()
					.eq(MsgTemplate::getTemplateType,msgTemplateType)
					.eq(MsgTemplate::getStatus,ConstantCode.STATUS_NOMAL_OLD)
					.eq(MsgTemplate::getTenantId,tenantId);

		List<MsgTemplate> msgTemplates = iMsgTemplateService.list(queryWrapper);
//		msgTemplates = translateMsgType(msgTemplates);
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,msgTemplates);
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 翻译消息模板类型
	 * @Param:
	 * @return:
	 * @Date: 2020/11/13
	 */
	private List<MsgTemplate> translateMsgType(List<MsgTemplate> msgTemplates) {
		if (CollectionUtils.isEmpty(msgTemplates)){
			return msgTemplates;
		}
		return msgTemplates.stream().map(msgTemplate -> {
			if (ConstantCode.MsgType.MSG.equals(msgTemplate.getTemplateType())) {
				msgTemplate.setTemplateTypeName(ConstantCode.MsgType.MSG_NAME);
			} else if (ConstantCode.MsgType.EMAIL.equals(msgTemplate.getTemplateType())) {
				msgTemplate.setTemplateTypeName(ConstantCode.MsgType.EMAIL_NAME);
			} else if (ConstantCode.MsgType.SYSTEM_MSG.equals(msgTemplate.getTemplateType())) {
				msgTemplate.setTemplateTypeName(ConstantCode.MsgType.SYSTEM_MSG_NAME);
			}
			return msgTemplate;
		}).collect(Collectors.toList());
	}

}
